package com.yadong.smarthome2.devicefinder;

import com.yadong.smarthome2.device.Device;
import com.yadong.smarthome2.messageparser.DeviceInfoParser;
import com.yadong.smarthome2.protocol2.ALog;
import com.yadong.smarthome2.udpbroadcast.BroadcastReceiveThread;
import com.yadong.smarthome2.udpbroadcast.BroadcastSenderTask;
import com.yadong.smarthome2.udpbroadcast.NewMessageListener;

public class WifiDeviceFinder implements DeviceFinder, NewMessageListener {
    private BroadcastReceiveThread mReceiveThread;
    private static final int CLIENT_BROADCAST_THREAD_PORT = 10082;
    private static final int SERVER_PROADCAST_THREAD_PORT = 10083;
    private DeviceInfoParser mDeviceInfoParser;
    private DeviceListener mDeviceListener;

    public WifiDeviceFinder() {
        mDeviceInfoParser = new DeviceInfoParser();
    }

    public boolean scanDevice(DeviceListener listener) {
        ALog.logd(this, "start scan wifi device");
        mReceiveThread = new BroadcastReceiveThread(SERVER_PROADCAST_THREAD_PORT);
        mReceiveThread.setMessageListener(this);
        if (!mReceiveThread.isThreadRuning()) {
            mReceiveThread.start();
        }

        // second send client broadcast to server.
        new BroadcastSenderTask(null)
            .execute(CLIENT_BROADCAST_THREAD_PORT + "",
                    "New_Client_in");

        mDeviceListener = listener;
        return true;
    }

    public boolean stopScan() {
        ALog.logd(this, "stop scan wifi device");
        mReceiveThread.stopReceive();
        return true;
    }

    @Override
    public void onNewMessageReceived(String threadName, String message) {
        ALog.logd(this, "on new message received....");
        Device device = mDeviceInfoParser.parseMessage(message);
        if(mDeviceListener != null && device != null) {
            mDeviceListener.onDeviceFinded(device);
        }
    }

}
